<?php
namespace plugins\member_login\controller;

use RongCloud\RongCloud;
use think\Db;
use plugins\member_login\validate\MemberValidate;

use plugins\member\model\MemberModel;

use cmf\controller\ApiThirdAccessBaseController;

use plugins\member\interfaceLib\MemberClassify;

use plugins\finance\model\FinanceModel;

define("APPKEY", 'p5tvi9dspe834');
define('APPSECRET', 'b8fHKCCpFMNe0N');

/**
 * 手机号码控制器
 */

class ApiPhoneController extends ApiThirdAccessBaseController

{

	public function regiest($param)
	{
		$data = $param['data'];

		//参数验证
		$check['phone'] = ['name'=>'手机号码','type'=>'require|regex:/^1[34578]\d{9}$/','message'=>['require'=>'手机号码不能为空','regex'=>'请输入正确的手机号码']];
		$check['code'] = ['name'=>'验证码'];
		checkParam($check,$data);

		//查重
		$check = MemberModel::get(['phone' => $data['phone']]);
		if($check){
			return api_json_echo( false , '该手机号已注册' );
		}

		//手机验证码检测
		$check_code = cmf_check_verification_code($data['phone'], $data['code'],true);

		if($check_code != ''){
			return api_json_echo( false , $check_code);
		}		

		//注册参数

		//随机的登录名
		$data['login_name'] = "user_".substr(uniqid(),0,6).mt_rand(1000,9999);
		$data['join_date'] = time();
		$data['join_ip'] = $this->request->ip();
		$data['password'] = empty($data['password']) ? '' : cmf_password($data['password']);

		//默认头像
		$data['head_portrait'] = '/plugins/member/view/public/user.png';

		$member = new MemberModel();

		$result =  $member->allowField( true )->save($data);

		if( !$result ){
			return api_json_echo( false , '注册失败' );
		}

		//uid的补充
	    $rand = str_pad($member->id,4,"0",STR_PAD_LEFT); 

		$member->uid = 'zy_'.$rand.mt_rand(1000,9999);

		$member->nick_name = $member->uid;

		//加密的uid
		$member->uid_aes = ( new MemberClassify )->aesSetUid($member->uid);
		$member->save();

		//返回反馈信息
		$return['token'] = $this->setIdentity($member->uid);
		$return['refresh_token'] = $this->setRefreshToken($member->uid);	
		$return['aes'] = $member->uid_aes;

		//创建财务账户
		 ( new FinanceModel )->createFinanceAccount('member',$member->uid);

		return api_json_echo( true , '会员注册成功',$return );

	}



	//手机验证码登陆
	public function login($param)
	{
        require 'RongCloud/RongCloud.php';
		$data = $param['data'];
		//验证参数
		$check['phone'] = ['name'=>'手机号码','type'=>'require|regex:/^1[34578]\d{9}$/','message'=>['regex'=>'请输入正确的手机号码']];
		$check['code'] = ['name'=>'验证码'];
		checkParam($check,$data);


        //没有直接注册    phone code
        $check_member = ( new MemberModel )->get(['phone'=>$data['phone']]);
        //该手机没有注册
        if($check_member == null){
            $this->regiest($param);
        }

		//手机验证码检测
		$check_code = cmf_check_verification_code($data['phone'], $data['code'],true);
		if($check_code != ''){
			return api_json_echo( false , $check_code);
		}

		$member = MemberModel::get(['phone'=>$data['phone']]);

		if($member->status == 1){


            $diviceid = '';    //设备号
            $cid = '';    //设备号
            if(!empty($data['diviceid'])){
                $diviceid = $data['diviceid'];
            }
            if(!empty($data['cid'])){
                $cid = $data['cid'];
            }

			//修改登陆时间与ip
			$result = $member->save([ 'last_date' => time() , 'last_ip' => $this->request->ip(),'diviceid' => $diviceid,'cid'=>$cid ]);
			if($result){
				//生成token
				$return['uid'] = $member->uid;
				$return['token'] = $this->setIdentity($member->uid);
				$return['refresh_token'] = $this->setRefreshToken($member->uid);
				$return['aes'] = $member->uid_aes;


                if(empty($member->token)){
                    $RongSDK = new RongCloud(APPKEY, APPSECRET);
                    $user = [
                        'id' => $member->uid,
                        'name' => $member->nick_name,//用户名称
                        'portrait' => ZY_APP_PATH.$member->head_portrait //用户头像
                    ];
                    $register = $RongSDK->getUser()->register($user);
                    if($register['code'] == 200){
                        Db::name('member')->where('uid',$member->uid)->update([
                            'token'=>$register['token']
                        ]);
                    }
                }



				return api_json_echo( true , '会员登录成功' , $return );
			}else{
				return api_json_echo( false , '会员登录失败，请检查号码' );
			}
		}else if($member->status == 2){
			return api_json_echo( false , '该用户被禁用，请重试' );
		}else if($member->status == 3){

		}
		return api_json_echo( false , '会员登录失败，请检查号码' );
	}



}